var ACTION = 'new';
var CUR_HORSE = '';
var HORSE_INDEX = 0;

$(document).ready(function(){
    //reset
    $('#reset').click(function(){
    	//enable all fields
        //$('#display_horse_form input[type=text]').attr('disabled','');
        //$('#display_horse_form select').attr('disabled','');        
        //set action = new
        ACTION = 'new';
        CUR_HORSE = '';
        
        $('#addHorse').attr('disabled','');
        $('.data_annual').each(function(){$(this).html(0);});
        $('#annualTotal').each(function(){$(this).html(0);}); 
        $('.data_cost').each(function(){$(this).val(0);});
        $('.data_freq').each(function(){$(this).val(0);});
    });
    
    // auto select when focusing on items
    $("body").delegate("input[type=text]", "focus", function(){
    	this.select();
    });
    
    // onhover data_item    
	$("body").delegate(".data_item", "hover", function(event){
		if( event.type === 'mouseenter' ){ 
        	$(this).children(".data_removeitem").show();
    	} else {
        	$(this).children(".data_removeitem").hide();
		}  
    });
    
    //add more items
    $("body").delegate('.data_additem','click', function(){
        $('<div class="data_item">'
        + '<img src="images/delete-icon.gif" alt="delete" title="delete this item" class="data_removeitem" />\n\t'
        + '<input type="text" maxlength="255" value="Add New Item" class="data_title"/>\n\t'
        + '<input type="text" maxlength="255" value="0" class="data_cost"/>\n\t'
        + '<select class="data_freq">\n\t'
		+ '<option value="0" selected="selected">---Select---</option>\n\t\t'
        + '<option value="52" >Weekly</option>\n\t\t'
        + '<option value="12" >Monthly</option>\n\t\t'
        + '<option value="8.7" >6 Weekly</option>\n\t\t'
        + '<option value="6.5" >8 Weekly</option>\n\t\t'
        + '<option value="4" >Quarterly</option>\n\t\t'
        + '<option value="2" >6 Monthly</option>\n\t\t'
        + '<option value="1" >Annually</option>\n\t\t'
		+ '</select>\n\t'
        + '<label class="data_annual">0</label>\n\t'
        + '</div>').animate({opacity:"show"},"slow").insertAfter($(this).parents(".data_cate").children(".data_item").last());
        
    });
	
	//remove item
    $("body").delegate(".data_removeitem", "click", function(){
    	$(this).parents(".data_item").remove();
    });
	    
    // calculate annual cost
    $("body").delegate(".data_freq", "change", function(){
    	calculator();
    });
    $("body").delegate(".data_cost", "change", function(){
    	calculator();
    });
    
    //display horse 
    $("body").delegate("#listHorse li", "click", function(){
        displayHorse(this.id);
    });
    
    // add horse to it's "cage"
    $('#addHorse').click(function(){    	
        var data = '';
        // check if items' cost is added
        if(isNaN($('#annualTotal').html().substr(1)) || $('#annualTotal').html().substr(1)==0){alert('Please Insert Expense Cost Before Adding More Horse \n\tNote: Cost Item Should Be A Number'); return;}               
        
        // {"name":"horseA","weight":"20","age":"2","fields":{"VET":[{"title":"Vaccinations","cost":"10","freq":"121","annual":"1440"},{"title":"Worming","cost":"23","freq":"19","annual":"20"}],"HORSECARE":[{"title":"cham soc","cost":"10","freq":"11","annual":"110"}]},"total":"2030"}
        // add data
        data += '"name":"'+$('#name').val()+'","weight":"'+$('#weight').val()+'","age":"'+$('#age').val()
        		+ '","fields":{';
        var fieldsData='';
        $(".data_cate").each(function(){ 
        	fieldsData += ',"' + $(this).find('.data_catename').html() + '":[';
        	var strFieldData ='';
        	$(this).find('.data_item').each(function(){
        		strFieldData += ',' + '{"title":"'+$(this).find('.data_title').val()+'","cost":"'+$(this).find('.data_cost').val()+'","freq":"'+$(this).find('.data_freq').val()+'","annual":"'+$(this).find('.data_annual').html()+'"}'
        	});
        	strFieldData = strFieldData.substr(1);
        	fieldsData += strFieldData + ']';
        });
        fieldsData = fieldsData.substr(1);
        
        data += fieldsData + '},"total":"' + $("#annualTotal").html()+'"';
        if(ACTION == 'new'){
            if(confirm("Saving Your Horse, Are You Sure?")){
	        //save current data
    	        $('<li title="Click here to Edit your horse" id="horse'+HORSE_INDEX+'" data-horsedata=\'{'+data+'}\'><a href="#">Horse '+$("#name").val()+'</a><div id="totalAdded" >Total Price: '+$('#annualTotal').html()+'</div></li>').animate({opacity:"show"},"slow").appendTo($('#listHorse'));
	            HORSE_INDEX++;
            } else return false;	        
		} else {
            if(confirm("Updating Your Horse, Are You Sure?")){
			     $('li#'+CUR_HORSE).data("horsedata", $.parseJSON('{'+data+'}'));
			     $('li#'+CUR_HORSE).attr("data-horsedata", '{'+data+'}');
			     $('li#'+CUR_HORSE).html('<a href="#">Horse '+$("#name").val()+'</a><div id="totalAdded" >Total Price: '+$('#annualTotal').html()+'</div>');
			} else return false;
		}   
    });
    
})

function displayHorse(horseId) {
        //disable all fields
       // $('#display_horse_form input[type=text]').attr('disabled','disabled');
        //$('#display_horse_form select').attr('disabled','disabled');
        
        // set action = edit
        CUR_HORSE = horseId;
        ACTION = 'edit';
        
        //get data from horse
        $data = $("#"+horseId).data("horsedata"); 
        
		$("#name").val($data.name);
		$("#weight").val($data.weight);
		$("#age").val($data.age); 
		$("#annualTotal").html($data.total);
		// display fields    
		var strHtml = "";
		var strItems = '';
        $.each($data.fields, function(key, value){
        	strItems = '';
        	$.each (value, function(itemIndex, item){
        		strItems += '<div class="data_item">'
					        + '<img src="images/delete-icon.gif" alt="delete" title="delete this item" class="data_removeitem" />\n\t'
					        + '<input type="text" maxlength="255" value="'+item.title+'" class="data_title"/>\n\t'
					        + '<input type="text" maxlength="255" value="'+item.cost+'" class="data_cost"/>\n\t'
					        + '<select class="data_freq">\n\t'
							+ '<option value="0" '+(item.freq==0?'selected="selected"':'')+'>---Select---</option>\n\t\t'
					        + '<option value="52" '+(item.freq==52?'selected="selected"':'')+' >Weekly</option>\n\t\t'
					        + '<option value="12" '+(item.freq==12?'selected="selected"':'')+'>Monthly</option>\n\t\t'
                            + '<option value="8.7" '+(item.freq==8.7?'selected="selected"':'')+'>6 Weekly</option>\n\t\t'
                            + '<option value="6.5" '+(item.freq==6.5?'selected="selected"':'')+'>8 Weekly</option>\n\t\t'
					        + '<option value="4" '+(item.freq==4?'selected="selected"':'')+'>Quarterly</option>\n\t\t'
                            + '<option value="2" '+(item.freq==2?'selected="selected"':'')+'>6 Monthly</option>\n\t\t'
					        + '<option value="1" '+(item.freq==1?'selected="selected"':'')+'>Annually</option>\n\t\t'
							+ '</select>\n\t'
					        + '<label class="data_annual">'+item.annual+'</label>\n\t'
					        + '</div>\n';
        	});
        	strHtml += '<div id="cate_1" class="data_cate">\n'
    	   					+'<div><label class="data_catename">'+key+'</label></div>\n' + strItems 
							+ '<img src="images/add-icon.gif" alt="Add Items" title="Add New Item" class="data_additem" />\n'
						  + '</div>\n';
        });
        $('#display_horse_form').html(strHtml);
}

//calculating function
function calculator(){
    var f    = [],
        cost = 0,
        i    = 0,
        j    = 0,
        k    = 0,
        cost = [],
        itemCost= [],
        bool = true,
        total= 0;
    $('.data_cost').each(function(){
        if(isNaN($(this).val())){                 
            $(this).css({'background':'#FFFBBB','font-weight':'bold'});
            cost[i] = 0;
            i++;
            bool = false;
        }else{
            if($(this).val()==''){$(this).val(0)}
            $(this).css({'background':'#E9E9E9','font-weight':'normal'});
            cost[i] = $(this).val();
            i++;
        }
    });
    $('.data_freq').each(function(){
        f[j] = $(this).val();
        j++;
    });
    
    for(i=0;i<$('.data_cost').size();i++){
        itemCost[i]= parseInt(Math.round(cost[i]*f[i]*10))/10;
        total= parseInt(Math.round(total*10)+ Math.round(itemCost[i]*10))/10;
    }
    
    $('.data_annual').each(function(){        
        $(this).html(itemCost[k]);
        k++;
    });
    if(bool){$('#annualTotal').html('$'+total)}
    else{$('#annualTotal').html('Undefined');}
}

function printHorsePDF(){
	var horsedata = JSON.stringify($("#horseA").data("horsedata"));
	var strHorse = "[";
	$('#listHorse li').each(function(){
		strHorse += JSON.stringify($(this).data("horsedata")) + ",";
	});
	strHorse = strHorse.substr(0, strHorse.length-1);//bo dau phay "," cuoi cung
	strHorse += "]"
	$("#pdfData").val(strHorse);
	
	$('#pdfForm').submit();
	/*$.ajax({
      url: "include/printpdf.php",
      global: false,
      type: "POST",
      data: {id : "IDFDSAF"},
      dataType: "application/pdf",
      async:false,
      success: function(msg){
         //alert(msg);
      },
      error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError);
        } 
	});
	*/   
}
    